package com.iqilu.ksd.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.GalleryAdapter;
import com.iqilu.ksd.bean.GalleryItemBean;
import com.iqilu.ksd.bean.NewsBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.ShareUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.iqilu.ksd.widget.MultiTouchViewPager;
import com.jude.swipbackhelper.SwipeBackHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import me.relex.circleindicator.CircleIndicator;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/11/3.
 */

public class GalleryActivity extends BaseActivity implements View.OnClickListener {

    private LigDialog ligDialog;
    private NewsBean data;
    private ArrayList<GalleryItemBean> list;
    private UserBean user;
    private int cId;
    private int catId;
    private int position;
    private GalleryAdapter adapter;
    private MyApplication application;
    private Boolean fromNews = false;
    private Boolean fromJPush = false;
    private Boolean fromPaike = false;
    private Boolean fromLive = false;

    private RelativeLayout layFooter;
    private ImageView btBack;
    private ImageView btLove;
    private LinearLayout layComment;
    private TextView tvComment;
    private LinearLayout layLike;
    private ImageView imgLike;
    private TextView tvLike;
    private ImageView btShare;
    private MultiTouchViewPager vpContent;
    private LinearLayout layContent;
    private TextView tvTitle;
    private TextView tvPosition;
    private TextView tvDescription;
    private ScrollView layDescription;
    private CircleIndicator layIndicator;

    private static final int REQUEST_LOGIN = 2001;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);
        ShareSDK.initSDK(this);
        initView();
        application = (MyApplication) getApplication();
        user = ((MyApplication) getApplication()).getUser();
        Intent intent = getIntent();
        cId = intent.getIntExtra("id", 0);
        catId = intent.getIntExtra("catId", 0);
        position = intent.getIntExtra("position", 0);
        fromNews = intent.getBooleanExtra("fromNews", false);
        fromJPush = intent.getBooleanExtra("fromJPush", false);
        fromPaike = intent.getBooleanExtra("fromPaike", false);
        fromLive = intent.getBooleanExtra("fromLive", false);
        data = (NewsBean) intent.getSerializableExtra("news");
        if (data != null) {
            initViewPager();
        } else {
            getContent();
        }
        if (fromLive) {
            layFooter.setVisibility(View.GONE);
            layContent.setVisibility(View.GONE);
            layIndicator.setVisibility(View.VISIBLE);
        }
        if (fromNews || fromPaike) {
            layDescription.setVisibility(View.GONE);
        }
    }

    private void initView() {
        layFooter = getView(R.id.lay_footer);
        btBack = getView(R.id.bt_back);
        btLove = getView(R.id.bt_love);
        layComment = getView(R.id.lay_comment);
        tvComment = getView(R.id.tv_comment);
        layLike = getView(R.id.lay_like);
        imgLike = getView(R.id.img_like);
        tvLike = getView(R.id.tv_like);
        btShare = getView(R.id.bt_share);
        vpContent = getView(R.id.vp_content);
        layContent = getView(R.id.lay_content);
        tvTitle = getView(R.id.tv_title);
        tvPosition = getView(R.id.tv_position);
        tvDescription = getView(R.id.tv_description);
        layDescription = getView(R.id.lay_description);
        layIndicator = getView(R.id.lay_indicator);
        btBack.setOnClickListener(this);
        btLove.setOnClickListener(this);
        layComment.setOnClickListener(this);
        layLike.setOnClickListener(this);
        btShare.setOnClickListener(this);
    }

    private void initViewPager() {
        initBottom();
        tvTitle.setText("" + data.getTitle());
        tvDescription.setText("" + data.getGallery().get(0).getText());
        tvPosition.setText("1/" + data.getGallery().size());
        list = data.getGallery();
        List<String> mList = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            mList.add(list.get(i).getImg());
        }
        vpContent.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (data.getGallery() != null) {
                    if (TextUtils.isEmpty(data.getGallery().get(position).getText()) || fromLive) {
                        layDescription.setVisibility(View.GONE);
                    } else {
                        tvDescription.setText(data.getGallery().get(position).getText());
                        layDescription.setVisibility(View.VISIBLE);
                    }
                    tvPosition.setText("" + (position + 1) + "/" + data.getGallery().size());
                }
                if (position == 0) {
                    SwipeBackHelper.getCurrentPage(GalleryActivity.this).setSwipeBackEnable(true);
                } else {
                    SwipeBackHelper.getCurrentPage(GalleryActivity.this).setSwipeBackEnable(false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        adapter = new GalleryAdapter(getSupportFragmentManager(), mList);
        vpContent.setAdapter(adapter);
        vpContent.setCurrentItem(position);
        layIndicator.setViewPager(vpContent, mList.size());
    }

    public void initBottom() {
        if (fromPaike) {
            btLove.setVisibility(View.INVISIBLE);
            layComment.setVisibility(View.INVISIBLE);
            layLike.setVisibility(View.INVISIBLE);
            return;
        }
        if (data.getFavorited() != 0 && user != null) {
            btLove.setImageResource(R.drawable.bt_footer_love_blue);
        }
        if (data.getLiked() != 0 && user != null) {
            imgLike.setImageResource(R.drawable.bt_like_orange);
        }
//        tvLove
        tvComment.setText("" + data.getCommentnum());
        tvLike.setText("" + data.getLikenum());
    }

    private void back() {
        if (fromJPush && !application.getMainStarted()) {
            startActivity(new Intent(this, MainActivity.class));
        }
        finish();
    }

    private void getContent() {
        String url = Api.URL_ARTICLE + "?id=" + cId + "&catid=" + catId + "&platform=ios";
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(GalleryActivity.this, getString(R.string.waiting));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(GalleryActivity.this, R.string.content_null, Toast.LENGTH_SHORT).show();
                ligDialog.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                data = JSONUtils.requestDetail(response, "data", NewsBean.class);
                if (data == null) {
                    Toast.makeText(GalleryActivity.this, R.string.content_null, Toast.LENGTH_SHORT).show();
                    ligDialog.dismiss();
//                    finish();
                    return;
                }
                initViewPager();
            }
        });
    }

    private void toShare() {
        if(data == null) return;
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(data.getTitle());
        sp.setTitleUrl(data.getShareurl()); // 标题的超链接
        sp.setText(data.getDescription());
        sp.setSiteUrl(data.getShareurl());
        sp.setUrl(data.getShareurl());
        sp.setImageUrl(data.getThumb());//分享网络图片
        sp.setSite(getString(R.string.app_name));
        ShareUtils.getInstance().setShareParams(this, sp).show();
    }

    public void toggleHide() {
        if (fromLive) return;
        if (layContent.getVisibility() == View.VISIBLE) {
            layContent.setVisibility(View.GONE);
        } else {
            layContent.setVisibility(View.VISIBLE);
        }
    }

    private void toComment() {
        Intent intent = new Intent(this, CommentActivity.class);
        intent.putExtra("articleid", data.getId());
        intent.putExtra("catid", data.getCatid());
        intent.putExtra("type", data.getType());
        startActivity(intent);
    }

    private void toLove() {
        if (user == null || user.getId() == 0) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, REQUEST_LOGIN);
            return;
        }
        if (data.getFavorited() == 1) {
            delFavorite();
        } else {
            addFavorite();
        }
    }

    // 点赞
    void toLike() {
        if (user == null || user.getId() == 0) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, REQUEST_LOGIN);
            return;
        }
        if (data.getLiked() != 1) {
            addLike();
        } else {
            delLike();
        }
    }

    // 添加收藏
    private void addFavorite() {
        String url = Api.URL_FAVORITE;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("articleid", "" + data.getId())
                .addParams("title", "" + data.getTitle())
                .addParams("catid", "" + data.getCatid())
                .addParams("type", "" + data.getType())
                .addParams("url", "" + data.getUrl())
                .addParams("thumb", "" + data.getThumb())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(GalleryActivity.this, R.string.favorite_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
                            Toast.makeText(GalleryActivity.this, R.string.favorite_add_success, Toast.LENGTH_SHORT).show();
                            btLove.setImageResource(R.drawable.bt_footer_love_blue);
                            data.setFavorited(1);
                        } else {
                            Toast.makeText(GalleryActivity.this, R.string.favorite_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    // 删除收藏
    private void delFavorite() {
        int id = data.getId();
        String type = data.getType();
        String url = Api.URL_FAVORITE + "?articleid=" + id + "&type=" + type;
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(GalleryActivity.this, R.string.favorite_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    Toast.makeText(GalleryActivity.this, R.string.favorite_del_success, Toast.LENGTH_SHORT).show();
                    btLove.setImageResource(R.drawable.bt_footer_love_black);
                    data.setFavorited(0);
                } else {
                    Toast.makeText(GalleryActivity.this, R.string.favorite_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 点赞
    private void addLike() {
        String url = Api.URL_ARTICLE_LIKE + "?id=" + data.getId() + "&catid=" + data.getCatid() + "&type=" + data.getType();
        String query = "id=" + data.getId() + "&catid=" + data.getCatid() + "&type=" + data.getType();
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(query)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(GalleryActivity.this, R.string.like_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
                            Toast.makeText(GalleryActivity.this, R.string.like_add_success, Toast.LENGTH_SHORT).show();
                            imgLike.setImageResource(R.drawable.bt_like_orange);
                            int count = Integer.valueOf("" + tvLike.getText()) + 1;
                            tvLike.setText("" + count);
                            data.setLiked(1);
                        } else {
                            Toast.makeText(GalleryActivity.this, R.string.like_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    // 取消点赞
    private void delLike() {
        String url = Api.URL_ARTICLE_LIKE + "?id=" + data.getId() + "&catid=" + data.getCatid() + "&type=" + data.getType();
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(GalleryActivity.this, R.string.like_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    Toast.makeText(GalleryActivity.this, R.string.like_del_success, Toast.LENGTH_SHORT).show();
                    imgLike.setImageResource(R.drawable.bt_like);
                    int count = Integer.valueOf("" + tvLike.getText()) - 1;
                    count = Math.max(0, count);
                    tvLike.setText("" + count);
                    data.setLiked(0);
                } else {
                    Toast.makeText(GalleryActivity.this, R.string.like_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_back:
                back();
                break;
            case R.id.bt_love:
                toLove();
                break;
            case R.id.lay_comment:
                toComment();
                break;
            case R.id.lay_like:
                toLike();
                break;
            case R.id.bt_share:
                toShare();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_LOGIN:
                    user = application.getUser();
                    break;
                default:
                    break;
            }
        }
    }

}
